<template>
  <div>
    <div class="my-list-header">
      <div class="title">{{ whoseHomepage }}的动态</div>
    </div>
    <div class="custom-table p-x-16">
      <template v-for="item in activities">
        <component-activities-list-item v-if="item.version === 1" :key="item.id" :item="item" />
        <component-activities-list-item-v2 v-if="item.version === 2" :key="item.id" :item="item" />
      </template>
    </div>
    <window-bottom-load
      :loading="loading"
      :no-more="!nextPage"
      @load="loadActivities"
    />
  </div>
</template>

<script>
import { mapGetters } from 'vuex';
import { formatActivities } from '@/views/users/show/lists/activities-list/format';
import ComponentActivitiesListItem from '@/components/users/show/activities/component-activities-list-item';
import ComponentActivitiesListItemV2 from '@/views/users/show/lists/activities-list/component-activities-list-item';
import WindowBottomLoad from '@/components/window-bottom-load';

export default {
  name: 'activities-list',
  components: {
    ComponentActivitiesListItem,
    ComponentActivitiesListItemV2,
    WindowBottomLoad,
  },
  props: {
    curTab: String,
  },
  data() {
    return {
      activities: [],
      loading: false,
      nextPage: null,
    };
  },
  computed: {
    ...mapGetters(['whoseHomepage']),
    // 加载动态数据所需参数
    loadActivitiesParams() {
      return {
        userId: this.$route.params.userId,
        page: this.nextPage || 1, // 加载页数
      };
    },
    loadActivitiesTriggerParams() {
      return {
        curTab: this.curTab, // this=activities
        userId: this.userId,
      };
    },
  },
  methods: {
    // 加载动态数据
    loadActivities() {
      this.loading = true;
      this.$api.users.activities(this.loadActivitiesParams)
        .then((res) => {
          this.activities = this.activities.concat(formatActivities(res.data));
          this.nextPage = res.kaminari.next_page;
        })
        .catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 清空本类别数据
    clearActivities() {
      this.activities = [];
      this.nextPage = null;
    },
  },
  watch: {
    loadActivitiesTriggerParams(newVal, oldVal) {
      const userChanged = newVal.userId !== oldVal.userId; // 用户是否改变
      const isCurTab = newVal.curTab === 'activities'; // 是否激活当前类别
      const tabIntoCur = isCurTab && (oldVal.curTab !== 'activities'); // 从别的类型切换过来的
      const curNoData = !this.activities.length;

      if (userChanged) {
        this.clearActivities();
        if (isCurTab) {
          this.loadActivities(); // 如果在当前页面改变了用户
          return;
        }
      }

      if (tabIntoCur && curNoData) {
        this.loadActivities();
      }
    },
  },
};
</script>

<style></style>
